from service.data import BusinessErrorCode, BusinessErrorMes
from service.handle_format import get_public_private_attribute, get_handle_to_proxy, get_company_info, request_handle_proxy, get_public_private_attribute_second
from service.common import insert_data, find_data, update_data, delete_data, get_condition
from pao_python.pao.data import process_db, dataframe_to_list, data_to_string_date, JsonRpc2Error, DataProcess
import json
import requests
import pymongo
import pandas as pd
from pao_python.pao.service.security.security_service import LoginService
import uuid
import time


class Classify(DataProcess):
    # 查询分类列表
    def get_product_classify_list(self, condition, page, count):
        res = {'result': []}

        def process_func(db):
            nonlocal res
            cols = db['IDMIS_Handle']
            new_condition = get_condition(condition)
            new_condition['handle_type'] = 'classify'

            if page and count:
                data_list = list(cols.find(new_condition)[
                                 (page-1)*count:(page-1)*count+count])
            else:
                data_list = list(cols.find(new_condition)[:])
            res['total'] = cols.find(new_condition).count()
            if len(data_list) > 0:
                for x in data_list:
                    otherStyleTime = data_to_string_date(x['create_date'])
                    x['create_date'] = otherStyleTime
                pd_equit = pd.DataFrame(data_list).drop(['_id'], axis=1)
                res['result'] = dataframe_to_list(pd_equit)

        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        return res
    # 查询父级分类列表

    def get_parent_list(self, condition, page, count):
        res = {'result': []}

        def process_func(db):
            nonlocal res
            cols = db['IDMIS_Handle']
            new_condition = get_condition(condition)
            new_condition['handle_type'] = {'$in': ['company', 'classify']}
            if page and count:
                data_list = list(cols.find(new_condition)[
                                 (page-1)*count:(page-1)*count+count])
            else:
                data_list = list(cols.find(new_condition)[:])
            res['total'] = cols.find(new_condition).count()
            if len(data_list) > 0:
                for x in data_list:
                    otherStyleTime = data_to_string_date(x['create_date'])
                    x['create_date'] = otherStyleTime
                pd_equit = pd.DataFrame(data_list).drop(['_id'], axis=1)
                res['result'] = dataframe_to_list(pd_equit)

        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        return res

    # 根据id获取产品分类信息
    def get_product_classify(self, id):
        res = {}

        def process_func(db):
            nonlocal res
            res_attribute = []
            handle_mes = find_data(db, 'IDMIS_Handle', {'id': id})

            attribute_mes = find_data(db, 'IDMIS_Attribute', {'handle_id': id})

            for x in attribute_mes[0]['attribute_data']:
                if(x['sign_key'] == 'custom_attribute'):
                    res_attribute = x['sign_value']
            handle_mes[0]['custom_attribute'] = res_attribute
            print('handle_mes', handle_mes)
            if (len(handle_mes) > 0):
                res = dataframe_to_list(pd.DataFrame(
                    handle_mes).drop(['_id'], axis=1))[0]
        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        return res

    # 删除模版信息
    def delete(self, handle_id):
        res = False

        def process_func(db):
            nonlocal res
            parent_handle_list = find_data(db, 'IDMIS_Handle', {
                'parent_id': {'$in': handle_id}})
            if len(parent_handle_list) > 0:
                return res
            # 缓存将删除的数据，若proxy删除失败，则需恢复本地数据
            handle_list = find_data(db, 'IDMIS_Handle', {
                                    'id': {'$in': handle_id}})

            handle_code_list = list(pd.DataFrame(
                handle_list)['handle_code'].values)
            arttribute_list = find_data(db, 'IDMIS_Attribute', {
                                        'handle_id': {'$in': handle_id}})
            # 若是企业标识，还需删除企业信息
            # 删除
            del_handle = delete_data(db, 'IDMIS_Handle', {
                                     'id': {'$in': handle_id}})
            del_attribute = delete_data(db, 'IDMIS_Attribute', {
                                        'handle_id': {'$in': handle_id}})
            if del_handle and del_attribute:
                res = True
            else:
                insert_data(db, 'IDMIS_Handle', handle_list[0])
                insert_data(db, 'IDMIS_Attribute', arttribute_list[0])
        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        return res

    # 新增/修改模版信息
    def insert(self, data, is_insert):
        res = False
        print('data', data)

        def process_func(db):
            # data_info = get_company_info(data)
            handle_type = data['handle_type']
            # data['handle_code'] = ''
            if is_insert:
                # has_handle = find_data(db, 'IDMIS_Handle', {
                #     'handle_code': data['handle_code']})
                # insert_company_result = True  # 若标识为企业标识
                company_info = {}
                # 数据格式化处理,分为'public'字段标识表记录,和'private'字段类目属性表字段
                # 模拟user_id
                attribute_dict = get_public_private_attribute_second(
                    data, handle_type, db)
                print('ee', attribute_dict)
                # 新建标识
                if attribute_dict['operate_type']:
                    # if len(has_handle) > 0:
                    #     raise JsonRpc2Error(
                    #         BusinessErrorCode.HANDLE_EXIST, BusinessErrorMes.HANDLE_EXIST)
                    if handle_type == 'company':
                        insert_company_result = insert_data(
                            db, 'IDMIS_Company', company_info)
                    insert_public_result = insert_data(
                        db, 'IDMIS_Handle', attribute_dict['public'])  # 创建标识记录
                    insert_private_result = insert_data(
                        db, 'IDMIS_Attribute', attribute_dict['private'])  # 创建类目属性记录
                    # 创建关联标识
                    if insert_public_result and insert_private_result:
                        res = True
                    # handle_result = insert_data(db, 'IDMIS_Handle', data_info)
                    # if handle_result:
                    #     handle_result = insert_data(db, 'IDMIS_Handle', data_info)
            else:
                attribute_dict = get_public_private_attribute(
                    data, handle_type, db)
                # 备份数据
                backup_handle = find_data(
                    db, 'IDMIS_Handle', {'id': data['id']})[0]
                backup_attribute = find_data(db, 'IDMIS_Attribute', {
                                             'handle_id': data['id']})[0]
                update_public_result = update_data(
                    db, 'IDMIS_Handle', attribute_dict['public'], {'id': data['id']})
                update_private_result = update_data(
                    db, 'IDMIS_Attribute', attribute_dict['private'], {'handle_id': data['id']})
                if update_public_result and update_private_result:
                    res = True
                else:
                    update_data(db, 'IDMIS_Handle', backup_handle,
                                {'id': data['id']})
                    update_data(db, 'IDMIS_Attribute', backup_attribute, {
                                'handle_id': data['id']})
        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        return res

     # 根据id获取产品分类信息
    def get_custom_attribute_list(self, id):
        res = {'custom_attribute': [],
               'company_handle_code': '', 'company_handle_name': ''}

        def process_func(db):
            nonlocal res
            isEnd = True
            custom_attribute = []
            parent_id = id
            while isEnd:
                handle_mes = find_data(db, 'IDMIS_Handle', {'id': parent_id})
                if len(handle_mes) > 0 and handle_mes[0]['handle_type'] == 'classify':
                    res_mes = find_data(db, 'IDMIS_Attribute', {
                                        'handle_id': parent_id})
                    if len(res_mes) > 0:
                        for x in res_mes[0]['attribute_data']:
                            if(x['sign_key'] == 'custom_attribute'):
                                custom_attribute.extend(x['sign_value'])
                    if handle_mes[0]['parent_id']:
                        parent_id = handle_mes[0]['parent_id']
                    else:
                        isEnd = False
                elif len(handle_mes) > 0 and handle_mes[0]['handle_type'] == 'company':
                    res['company_handle_code'] = handle_mes[0]['handle_code']
                    res['company_handle_name'] = handle_mes[0]['handle_name']
                    isEnd = False
                else:
                    isEnd = False
            print(custom_attribute, 'custom_attribute')
            res['custom_attribute'] = custom_attribute
        process_db(self.db_addr, self.db_port, 'IDMIS', process_func)
        return res
